package foxy;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

public class TCPClient {
	private Timer timer=new Timer();
	 // 信道选择器  
    private Selector selector;  
    static // 与服务器通信的信道  
    SocketChannel socketChannel;  
    // 要连接的服务器Ip地址  
    private String hostIp;  
    // 要连接的远程服务器在监听的端口  
    private int hostListenningPort;  
    public TCPClient(String HostIp, int HostListenningPort) throws IOException {  
        this.hostIp = HostIp;  
        this.hostListenningPort = HostListenningPort;  
        initialize();  
        timer.schedule(new TimerTask() {
			@Override
			public void run() {
				sendMsg("发送数据");
			}
		}, 10000,10000);
        
    }  
    /**  
     * 初始化  
     * @throws IOException  
     */  
    private void initialize() {  
    	//closeSocket();
        // 打开监听信道并设置为非阻塞模式  
        try {
			socketChannel = SocketChannel.open(new InetSocketAddress(hostIp,  
			        hostListenningPort));  
			socketChannel.configureBlocking(false);  
			// 打开并注册选择器到信道  
			selector = Selector.open();  
			socketChannel.register(selector, SelectionKey.OP_READ);  
			// 启动读取线程  
			new TCPClientReadThread(selector);
			mFlag=true;
		} catch (ClosedChannelException e) {
			System.out.println("服务器未打开");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("服务器未打开");
			e.printStackTrace();
		}  
    }  
    /**  
     * 发送字符串到服务器  
     *   
     * @param message  
     * @throws IOException  
     */  
    public void sendMsg(String message)  {  
    	if(mFlag){
    		try {
				ByteBuffer writeBuffer = ByteBuffer.wrap(message.getBytes("UTF-8"));  
				socketChannel.write(writeBuffer);
				} catch (IOException e) {
					  mFlag = false;  
	                    closeSocket();
	                    e.printStackTrace();  
				}
    	}else{
    		initialize();
    	}
    }  
    
    
    static TCPClient client;  
    public static boolean mFlag = true;  
   /* public static void main(String[] args) throws IOException {  
        client = new TCPClient("172.16.105.67", 1991);  
        new Thread() {  
            @Override  
            public void run() {  
                try {  
                    client.sendMsg("你好!Nio!醉里挑灯看剑,梦回吹角连营");  
                    while (mFlag) {  
                        Scanner scan = new Scanner(System.in);//键盘输入数据  
                        String string = scan.next();  
                        client.sendMsg(string);  
                    }  
                
                } finally {  
                    mFlag = false;  
                    try {
						socketChannel.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
                }  
                super.run();  
            }  
        }.start();  
    } 
    */
    
    void closeSocket(){
    	 mFlag = false; 
    	 try {
    		 if(socketChannel!=null){
				socketChannel.close();
				socketChannel=null;
    		 }
    		 if(selector!=null){
				 selector.close();
				 selector=null;
    		 }
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	
    }
    
    
}
